import React, { useCallback, useEffect, useState } from 'react';
import { ActionSheet, Button, Checkbox, Dialog, List, Popup, Toast } from 'antd-mobile';
import NavBar from '@/components/NavBar/NavBar';
import SubmitBar from '@/components/SubmitBar/SubmitBar';
import SvgIcon from '@/components/SvgIcon/SvgIcon';
import { useEnhanceDispatch, useEnhanceSelector } from '@/hooks';
import { findPatient } from '@/store/modules/patientStore';
import { useNavigate } from 'react-router-dom';
import { Patient } from '@/type/PatientType';
import { clearConsultInfo, createConsultOrder, fetchConsultOrderPre, paymentConsultOrder } from '@/store/modules/consultStore';
import { ConsultOrderPre, ConsultOrderPreParams, PaymentParams } from '@/type/ConsultType';
import doctor from '@/assets/images/avatar-doctor.svg';
import './ConsultPay.scss';


const ConsultPay = () => {
  const enhanceDispatch = useEnhanceDispatch();
  const consultInfo = useEnhanceSelector(state => state.consultStore.consultInfo);
  const navigate = useNavigate();
  // 患者ID
  const patientId = useEnhanceSelector(state => state.consultStore.consultInfo.patientId);
  // 问诊类型
  const type = useEnhanceSelector(state => state.consultStore.consultInfo.type);
  // 极速问诊级别
  const illnessType = useEnhanceSelector(state => state.consultStore.consultInfo.illnessType);
  // 病情描述
  const illnessDesc = useEnhanceSelector(state => state.consultStore.consultInfo.illnessDesc);
  // 患者详情
  const [patient, setPatient] = useState<Patient>({} as Patient);
  // 获取订单预支付信息的参数
  const [consultOrderPreParams, setConsultOrderPreParams] = useState<ConsultOrderPreParams>({ type, illnessType, useCoupon: '1' });
  // 订单预支付信息
  const [orderPreInfo, setOrderPreInfo] = useState<ConsultOrderPre>({} as ConsultOrderPre);
  //  是否同意支付协议
  const [isAgree, setIsAgree] = useState<boolean>(true);
  // 支付参数
  const [paymentConsultOrderParams, setPaymentConsultOrder] = useState<PaymentParams>({
    paymentMethod: 0,
    payCallback: 'http://localhost:80/room',
    orderId: '',
  });

  const [loading, setLoading] = useState<boolean>(false);

  // 左边插槽内容
  const left = useCallback(() => (<span>返回</span>), []);
  // 中间插槽内容
  const children = useCallback(() => (<span>支付信息</span>), []);
  // 是否显示支付弹框
  const [visible, setVisible] = useState(false);

  /**
   * @description 查询就诊人详情的回调函数
   * */
  const findPatientDetail = async () => {
    try {
      const patientDetail = await enhanceDispatch(findPatient(patientId as string)).unwrap();
      setPatient(patientDetail);
    } catch (rejectedValueOrSerializedError: any) {
      Toast.show(rejectedValueOrSerializedError);
    }
  };

  /**
   * @description 获取订单预支付信息的回调
   * */
  const fetchConsultOrder = async () => {
    try {
      const orderPre = await enhanceDispatch(fetchConsultOrderPre(consultOrderPreParams)).unwrap();
      setOrderPreInfo(orderPre);
    } catch (rejectedValueOrSerializedError: any) {
      Toast.show(rejectedValueOrSerializedError);
    }
  };


  /**
   * @description 提交订单按钮的回调函数
   * */
  const handleSubmitOrder = async () => {
    if (!isAgree) {
      Toast.show('请勾选支付协议');
      return;
    }
    try {
      setVisible(true);
      setLoading(true);
      Toast.show({ content: '订单提交中请稍等', icon: 'loading' });
      const { id: orderId } = await enhanceDispatch(createConsultOrder(consultInfo)).unwrap();
      setPaymentConsultOrder({ ...paymentConsultOrderParams, orderId: orderId });
      Toast.show({ icon: 'success', content: '提交订单成功' });
    } catch (rejectedValueOrSerializedError: any) {
      Toast.show(rejectedValueOrSerializedError);
    } finally {
      setLoading(false);
    }
  };

  /**
   * @description 点击立即支付按钮的回调函数
   * */
  const handlePayment = async () => {
    try {
      if (paymentConsultOrderParams.paymentMethod === 0 || paymentConsultOrderParams.paymentMethod === 2) {
        Toast.show('当前不支持此支付方式');
        return;
      }
      setLoading(true);
      const payUrl = await enhanceDispatch(paymentConsultOrder(paymentConsultOrderParams)).unwrap();
      window.location.href = payUrl;
    } catch (rejectedValueOrSerializedError: any) {
      Toast.show(rejectedValueOrSerializedError);
    } finally {
      setLoading(false);
    }
  };


  /**
   * @description 支付弹框组件关闭时候的回调函数
   * */
  const onMaskClick = async () => {
    const confirm = await Dialog.confirm({ content: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭?', header: '温馨提示', cancelText: '依然关闭', confirmText: '继续支付' });
    if (confirm) {
      Toast.show('请您继续支付');
    } else {
      enhanceDispatch(clearConsultInfo());
      navigate('/');
    }
  };

  useEffect(() => {
    findPatientDetail();
    fetchConsultOrder();
  }, []);

  return (
    <div className="consult-pay">
      {/*导航栏组件*/}
      <NavBar back={left()} children={children()} onBack={() => navigate(-1)}></NavBar>
      <div className="pay-info">
        <p className="tit">图文问诊 {orderPreInfo.actualPayment} 元</p>
        <img className="img" src={doctor}></img>
        <p className="desc">
          <span>极速问诊</span>
          <span>自动分配医生</span>
        </p>
      </div>
      <List>
        <List.Item title="优惠券" extra={`¥${orderPreInfo.couponDeduction || 0}`}></List.Item>
        <List.Item title="积分抵扣" extra={`¥${orderPreInfo.pointDeduction || 0}`}></List.Item>
        <List.Item title="应付款" extra={`¥${orderPreInfo.payment || 0}`}></List.Item>
        <List.Item title="实付款" extra={`¥${orderPreInfo.actualPayment || 0}`}></List.Item>
      </List>
      <div className="pay-space"></div>
      <List>
        <List.Item title="患者信息" extra={`${patient.name || '未知'} | ${patient.genderValue || '未知'} | ${patient.age || 0}岁`}></List.Item>
        <List.Item title="患者身份证" extra={`${patient.idCard || 0}`}></List.Item>
        <List.Item title="病情描述" extra={illnessDesc || '未知'}></List.Item>
      </List>
      <div className="pay-schema">
        <Checkbox checked={isAgree} onChange={(checked) => setIsAgree(checked)} style={{ '--icon-size': '17px' }}>我已同意 <span className="text">支付协议</span></Checkbox>
      </div>
      <SubmitBar left={<span>合计: <span className="price">￥{orderPreInfo.actualPayment} </span> </span>} right={<Button color="primary" onClick={handleSubmitOrder} loading={loading}>提交订单</Button>} />
      <Popup className="popup-par" visible={visible} onMaskClick={onMaskClick} bodyStyle={{ borderTopLeftRadius: '8px', borderTopRightRadius: '8px', minHeight: '40vh' }}>
        <div className="header">选择支付方式</div>
        <div className="total-price">￥{orderPreInfo.actualPayment?.toFixed(3) || 0}</div>
        <List>
          <List.Item extra={<Checkbox checked={paymentConsultOrderParams.paymentMethod === 0} onChange={() => setPaymentConsultOrder({ ...paymentConsultOrderParams, paymentMethod: 0 })} />}>
            <div className="paymethod">
              <SvgIcon name="wechat" width="20px" height="20px"></SvgIcon>
              <span>微信支付</span>
            </div>
          </List.Item>
          <List.Item extra={<Checkbox checked={paymentConsultOrderParams.paymentMethod === 1} onChange={() => setPaymentConsultOrder({ ...paymentConsultOrderParams, paymentMethod: 1 })} />}>
            <div className="paymethod">
              <SvgIcon name="alipay" width="20px" height="20px"></SvgIcon>
              <span>支付宝支付</span>
            </div>
          </List.Item>

          <List.Item extra={<Checkbox checked={paymentConsultOrderParams.paymentMethod === 2} onChange={() => setPaymentConsultOrder({ ...paymentConsultOrderParams, paymentMethod: 2 })} />}>
            <div className="paymethod">
              <SvgIcon name="cloud" width="20px" height="20px"></SvgIcon>
              <span>云闪付支付</span>
            </div>
          </List.Item>
        </List>
        <div className="payment">
          <Button color="primary" block onClick={handlePayment} loading={loading}>立即支付</Button>
        </div>
      </Popup>
    </div>
  );
};

export default ConsultPay;